// File Name: init.c
// Author: kukukukuku~
// Date: 2024-06-25

#include "./User/ADC/inc/adc_ctrl.h"
#include "./User/Beep/inc/beep_logic.h"
#include "./User/Debug/inc/debug_task.h"
#include "./User/Fan/inc/fan_ctrl.h"
#include "./User/Flash/inc/flash_task.h"
#include "./User/Key/inc/key_task.h"
#include "./User/LED/inc/led_task.h"
#include "./User/OLED/inc/oled_task.h"
#include "./User/RS485/inc/rs485_task.h"
#include "./User/Step_Motor/inc/step_motor_task.h"
#include "./User/Sys/inc/init.h"
#include "./User/WS2812B/inc/ws2812b_task.h"
#include "at32f421.h"
#include "at32f421_clock.h"
#include "FreeRTOS.h"
#include "task.h"

/**
 * @brief   系统初始化
 * @param   None
 * @retval  None
 * @note    None
*/
void sys_init(void)
{
    //配置系统时钟 内部源PLL-120Mhz AHB-div1 APB2-div1 APB1-div1
    system_clock_config();
    
    //中断优先级分组2
    nvic_priority_group_config(NVIC_PRIORITY_GROUP_2);
    
    adc_config();
    beep_config();
    debug_config();
    fan_config();
    key_config();
    led_config();
    oled_config();
    rs485_config();
    step_motor_config();
    ws2812b_config();
    
    flashReadFlag = flash_read();
    
    adc_ordinary_software_trigger_enable(ADC1, TRUE);
    
    beep_alarm(200);
}


/**
 * @brief   初始化任务
 * @param   arg:    任务参数
 * @retval  None
 * @note    None
*/
void task_init(void *arg)
{
    taskENTER_CRITICAL();
    //创建Debug任务
    xTaskCreate(task_debug, TASK_DEBUG_LABEL, TASK_DEBUG_STACK, NULL, TASK_DEBUG_PRIORITIES, &taskHandleDebug);
    //创建Flash任务
    xTaskCreate(task_flash, TASK_FLASH_LABEL, TASK_FLASH_STACK, NULL, TASK_FLASH_PRIORITIES, &taskHandleFlash);
    //创建Key任务
    xTaskCreate(task_key, TASK_KEY_LABEL, TASK_KEY_STACK, NULL, TASK_KEY_PRIORITIES, &taskHandleKey);
    //创建LED任务
    xTaskCreate(task_led, TASK_LED_LABEL, TASK_LED_STACK, NULL, TASK_LED_PRIORITIES, &taskHandleLed);
    //创建OLED任务
    xTaskCreate(task_oled, TASK_OLED_LABEL, TASK_OLED_STACK, NULL, TASK_OLED_PRIORITIES, &taskHandleOled);
    //创建RS485任务
    xTaskCreate(task_rs485, TASK_RS485_LABEL, TASK_RS485_STACK, NULL, TASK_RS485_PRIORITIES, &taskHandleRs485);
    //创建Step_Motor任务
    xTaskCreate(task_step_motor, TASK_STEP_MOTOR_LABEL, TASK_STEP_MOTOR_STACK, NULL, TASK_STEP_MOTOR_PRIORITIES, &taskHandleStepMotor);
    //创建WS2812B任务
    xTaskCreate(task_ws2812b, TASK_WS2812B_LABEL, TASK_WS2812B_STACK, NULL, TASK_WS2812B_PRIORITIES, &taskHandleWs2812b);

    //创建Flash二值信号量
    if((semaphBinFlash = xSemaphoreCreateBinary()) == NULL)
    {
        while(1);
    }
    
    //创建Step_Motor二值信号量
    if((semaphBinStepMotor = xSemaphoreCreateBinary()) == NULL)
    {
        while(1);
    }
    
    taskEXIT_CRITICAL();
    
    vTaskDelete(NULL);
}
